<?php

namespace app\common\model;

use think\Model;
use think\facade\Cache;

class IpVisit extends Model
{
    protected $table = 'ip_visits';


    // 计算当天剩余秒数
    function getTodayRemainingSeconds()
    {
        $now = time();
        $tomorrow = strtotime('tomorrow');
        return $tomorrow - $now;
    }
    
    // 设置当天有效缓存
    function setTodayCache($key, $value)
    {
        $expire = $this->getTodayRemainingSeconds();
        Cache::set($key, $value, $expire);
    }
    
    // 获取缓存
    function getTodayCache($key)
    {
        return Cache::get($key);
    }



    public function recordIpVisit()
    {
        $ip = request()->ip();
        $isCache = $this->getTodayCache($ip);
        // echo $isCache;
        $date = date('Y-m-d');
        if (empty($isCache)) {
            $this->setTodayCache($ip,1);
            IpVisit::create([
                'create_time' => date('Y-m-d H:i:s'),
                'ip' => $ip,
                'visit_date' => $date
            ]);
        }
    }
}